<template>
  <breadCrumb :item="item" ref="breadcrumb"></breadCrumb>
  <!-- 外壳 -->
	<div class="common-wrapped">
		<!-- 内容 -->
		<div class="common-content">
      <el-tabs v-model="activeName" class="demo-tabs">
        <!-- 1. 账号详情 -->
        <el-tab-pane label="账号详情" name="first">
          <!-- 1-1. 用户头像 -->
          <div class="account-info-wrapped">
            <span>用户头像：</span>
            <div class="account-info-content">
								<!-- :show-file-list="false"：表示不显示已上传文件的列表; action是上传头像的接口-->
								<el-upload class="avatar-uploader" :action="avatarUrl" :show-file-list="false" 
									:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
									<img v-if="userStore.imageUrl" :src="userStore.imageUrl" class="avatar">
									<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
								</el-upload>
            </div>
          </div>
          <!-- 1-2. 用户账号 -->
          <div class="account-info-wrapped">
						<span>用户账号：</span>
						<div class="account-info-content">
              <!-- disabled 属性使该输入框处于禁用状态 -->
							<el-input v-model="userData.account" disabled></el-input>
						</div>
					</div>
          <!-- 1-3. 用户密码 -->
					<div class="account-info-wrapped">
						<span>用户密码：</span>
						<div class="account-info-content">
							<el-button type="primary" @click="openChangePassword">修改密码</el-button>
						</div>
					</div>
          <!-- 1-4. 用户姓名 -->
					<div class="account-info-wrapped">
						<span>用户姓名：</span>
						<div class="account-info-content">
							<el-input v-model="userData.name"></el-input>
						</div>
						<div class="account-save-button">
							<el-button type="primary" @click="saveName">保存</el-button>
						</div>
					</div>
          <!-- 1-5. 用户性别 -->
					<div class="account-info-wrapped">
						<span>用户性别：</span>
						<div class="account-info-content">
							<!-- <el-input v-model="userData.sex"></el-input> -->
							<el-select v-model="userData.sex" placeholder="请选择性别" style="width: 240px;">
								<el-option label="男" value="男"></el-option>
								<el-option label="女" value="女"></el-option>
							</el-select>
						</div>
						<div class="account-save-button">
							<el-button type="primary" @click="saveSex">保存</el-button>
						</div>
					</div>
          <!-- 1-6. 用户身份 -->
					<div class="account-info-wrapped">
						<span>用户身份：</span>
						<div class="account-info-content">
							<el-input v-model="userData.identity" disabled></el-input>
						</div>
					</div>
           <!-- 1-7. 用户部门 -->
					<div class="account-info-wrapped">
						<span>用户部门：</span>
						<div class="account-info-content">
							<el-input v-model="userData.department" disabled></el-input>
						</div>
						<!-- <div class="account-save-button">
							<el-button type="primary" @click="saveDepartment">保存</el-button>
						</div> -->
					</div>
          <!-- 1-8. 用户邮箱 -->
					<div class="account-info-wrapped">
						<span>用户邮箱：</span>
						<div class="account-info-content">
							<el-input v-model="userData.email"></el-input>
						</div>
						<div class="account-save-button">
							<el-button type="primary" @click="saveEmail">保存</el-button>
						</div>
					</div>
        </el-tab-pane>

        <!-- 2. 公司信息 -->
        <el-tab-pane label="公司信息" name="second" v-if="userStore.identity==='超级管理员'">
          <!-- 2.1 公司名称 -->
          <div class="account-info-wrapped">
						<span>公司名称</span>
						<div class="account-info-content">
							<el-input v-model="companyName"></el-input>
						</div>
						<div class="account-save-button">
							<el-button type="primary" @click="resetCompanyName">保存</el-button>
						</div>
					</div>
          <!-- 2.2 公司介绍 -->
					<div class="account-info-wrapped">
						<span>公司介绍</span>
						<div class="account-info-content">
							<el-button type="success" @click="openEditor(1)">编辑公司介绍</el-button>
						</div>
					</div>
          <!-- 2.3 公司架构 -->
					<div class="account-info-wrapped">
						<span>公司架构</span>
						<div class="account-info-content">
							<el-button type="success" @click="openEditor(2)">编辑公司架构</el-button>
						</div>
					</div>
          <!-- 2.4 公司战略 -->
					<div class="account-info-wrapped">
						<span>公司战略</span>
						<div class="account-info-content">
							<el-button type="success" @click="openEditor(3)">编辑公司战略</el-button>
						</div>
					</div>
          <!-- 2.5 公司高层 -->
					<div class="account-info-wrapped">
						<span>公司高层</span>
						<div class="account-info-content">
							<el-button type="success" @click="openEditor(4)">编辑公司高层</el-button>
						</div>
					</div>
        </el-tab-pane>

        <!-- 3. 首页管理 轮播图-->
        <el-tab-pane label="首页管理" name="third" v-if="userStore.identity==='超级管理员'">
          <div class="home-wrapped">
            <div class="tips"><span>提示: 点击图片框进行切换首页轮播图</span></div>
            <!-- 轮播图 -->
						<div class="swiper-wrapped" v-for="(item, index) in swiperData" :key="index">
							<div class="swiper-name">轮播图{{index+1}}:&nbsp;&nbsp;</div>
							<el-upload class="avatar-uploader" :action="swiperUrl" :show-file-list="false" 
								:on-success="handleSwiperSuccess" :before-upload="beforeAvatarUpload" :data="item">
								<!-- 这个:data='item'就是swiper1/swiper2/... -->
								<template #trigger>
									<img v-if="imageSwiperUrl[index]" :src="imageSwiperUrl[index]" class="swiper" />
									<img src="@/assets/雪碧图.png" v-else>
								</template>
							</el-upload>
						</div>
          </div>
        </el-tab-pane>

        <!-- 4. 其他设置 -->
        <el-tab-pane label="其他设置" name="fourth" v-if="userStore.identity==='超级管理员'">
          <div class="other-set">
            <!-- 4.1 部门设置 -->
						<div class="department-set">
							<span>部门设置</span>
							<el-tag v-for="tag in dynamicDepartmentTags" :key="tag" class="mx-1" closable :disable-transitions="false" 
											@close="handleDepartmentClose(tag)">{{ tag }}</el-tag>
							<el-input v-if="inputDepartmentVisible" ref="InputDepartmentRef" v-model="inputDepartmentValue" class="ml-1 w-20" size="small" 
												@keyup.enter="handleInputDepartmentConfirm" @blur="handleInputDepartmentConfirm" />
							<el-button v-else class="button-new-tag ml-1" size="small" @click="showDepartmentInput">+ 添加部门</el-button>
						</div>
            <!-- 4.2 产品设置 -->
						<div class="product-set">
							<span>产品设置</span>
							<el-tag v-for="tag in dynamicProductTags" :key="tag" class="mx-1" closable :disable-transitions="false" 
											 @close="handleProductClose(tag)">{{ tag }}</el-tag>
							<el-input v-if="inputProductVisible" ref="InputProductRef" v-model="inputProductValue" class="ml-1 w-20" size="small" 
							         @keyup.enter="handleInputProductConfirm" @blur="handleInputProductConfirm" />
							<el-button v-else class="button-new-tag ml-1" size="small" @click="showProductInput">+ 添加产品</el-button>
						</div>
					</div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>

	<!-- 修改密码弹窗 -->
	<changePasswordComp ref="changeP"></changePasswordComp>
	<!-- 编辑公司信息弹窗 -->
	<editor ref="editorP"></editor>
</template>
 
<script setup lang="ts">
  import { onMounted, reactive, ref, nextTick, toRaw } from 'vue';
  import { ElMessage } from 'element-plus';
  import breadCrumb from '@/components/bread_crumb.vue';
  import type { ElInput, UploadProps } from 'element-plus';  // elementplus
  import { Plus } from '@element-plus/icons-vue';
  import { changeName, changeSex, changeEmail, getUserInfo, changeDepartment } from '@/api/userinfor.js';
	import { useUserInfo } from '@/store/userinfor.js';
	import { bind } from '@/api/userinfor.js'; // 绑定账号和头像
	import changePasswordComp from './components/change_password.vue'; //  修改密码弹窗

	// uploadSwiper的功能被swiper组件做了
	import { 
		uploadSwiper, getAllSwiper, 
		getCompanyName, changeCompanyName,
		setDepartment, getDepartment,
		setProduct, getProduct,
	} from '@/api/setting.js';  // 公司信息，部门，产品
	import { bus } from "@/utils/mitt.js";
	import editor from './components/editor.vue'; // 编辑公司弹窗

	const userStore = useUserInfo()  // pinia
	// const textData = ref("ljszl")

  interface userData {
		account: number,
		name: string,
		sex: string,
		identity: string,
		department: string,
		email: string,
	}
  const userData: userData = reactive({
		account: null,
		name: '',
		sex: '',
		identity: '',
		department: '',
		email: '',
	})

  onMounted(async () => {
		let id = localStorage.getItem('id')
		const res = await getUserInfo(id)
		userData.account = res.data.account
		userData.name = res.data.name
		userData.sex = res.data.sex
		userData.identity = res.data.identity
		userData.department = res.data.department
		userData.email = res.data.email
	})

	const breadcrumb = ref() // 面包屑
	const item = ref({       // 面包屑参数
		first: '系统设置',
	})

  // 默认打开的标签页  el-tabs带的
	const activeName = ref('first')

  // -----------------------------------------------------------------------用户信息
  // 用户头像地址 handleAvatarSuccess beforeAvatarUpload
  // const avatarUrl = ref('http://127.0.0.1:3007/user/uploadAvatar')
	const avatarUrl = ref(`${import.meta.env.VITE_API_BASEURL}/user/uploadAvatar`) 

	// 头像上传成功的函数, 提供了点击文件图片的框，点击可以选择图片上传(不是我们写的，elementplus提供)
  const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => { 
		if(response.status == 0){
			userStore.$patch({
				imageUrl: response.url
			})
			ElMessage({
				message:'头像更新成功',
				type: 'success',
			}); // ``;``要加
			(async ()=>{
				// const res = await bind(userStore.account, response.onlyId, response.url)
				// console.log(res);
				await bind(userStore.account, response.onlyId, response.url)
			})()  // 立即执行
		}else{
			ElMessage.error('更新头像失败，请重新上传')
		}
  }
	// 头像上传前函数
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
      ElMessage.error('图片必须是jpg格式')
      return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('图片必须小于2MB')
      return false
    }
    return true
  }

  // 修改密码
	const changeP = ref()
  const openChangePassword = () => {
		changeP.value.open()
  }

  // 保存用户姓名
  const saveName = async () => {
		const res = await changeName(userData.name, localStorage.getItem('id'))
		if (res.data.status == 0) {
			userStore.name = userData.name; // 解决在系统设置修改姓名时，头部姓名不更新问题
			ElMessage({
				message: '修改成功',
				type: 'success',
			})
		} else {
			ElMessage.error('修改姓名失败，请重新输入！')
		}
  }
  // 保存用户性别
  const saveSex = async () => {
		const res = await changeSex(userData.sex, localStorage.getItem('id'))
		if (res.data.status == 0) {
			userStore.sex = userData.sex;
			ElMessage({
				message: '修改成功',
				type: 'success',
			})
		} else {
			ElMessage.error('修改性别失败，请重新输入！')
		}
  }
  // 保存用户邮箱
  const saveEmail = async () => {
		const res = await changeEmail(userData.email, localStorage.getItem('id'))
		if (res.data.status == 0) {
			userStore.email = userData.email;
			ElMessage({
				message: '修改成功',
				type: 'success',
			})
		} else {
			ElMessage.error('修改邮箱失败，请重新输入！')
		}
	}
	// 保存用户部门
	const saveDepartment = async () => {
		const res = await changeDepartment(userData.department, localStorage.getItem('id'))
		if (res.data.status == 0) {
			userStore.department = userData.department;
			ElMessage({
				message: '修改成功',
				type: 'success',
			})
		} else {
			ElMessage.error('修改部门失败，请重新输入！')
		}
	}

  // -----------------------------------------------------------------------公司信息
	const companyName = ref() // 公司名称
	const returnCompanyName = async() => { 
		const res = await getCompanyName()
		companyName.value = res.data
	}
	returnCompanyName()

  // 修改公司名称
  const resetCompanyName = async() => {
		const res = await changeCompanyName(companyName.value)
		if(res.data.status == 0){
			ElMessage({
				message: '修改公司名称成功',
				type: 'success',
			})
		}else{
			ElMessage.error('修改公司名称失败，请重新输入！')
		}
  }
  // 打开公司信息编辑弹窗 
	const editorP = ref()
  const openEditor = (id:number) => {
    bus.emit('editorTitle', id) //  第一个参数是标记, 第二个参数要传入的值 
		editorP.value.open()
  }

  // -----------------------------------------------------------------------首页管理
	// :action="swiperUrl"是上传轮播图的接口
	const imageSwiperUrl = ref([])
  // const swiperUrl = ref('http://127.0.0.1:3007/set/uploadSwiper')
	const swiperUrl = ref(`${import.meta.env.VITE_API_BASEURL}/set/uploadSwiper`)
	
  const swiperData = ref([
    { name: 'swiper1'}, // 后端把set_name改为name
    { name: 'swiper2'}, 
    { name: 'swiper3'}, 
    { name: 'swiper4'}, 
    { name: 'swiper5'}, 
    { name: 'swiper6'},
  ])
	// 上传轮播图成功
	const handleSwiperSuccess: UploadProps['onSuccess'] = (res) => {
		// console.log(res);  // :data属性
		if(res.status == 0){
			returnAllSwiper()
			ElMessage({
				message:'轮播图更新成功',
				type: 'success',
			}); 
		}else{
			ElMessage.error('更新轮播图失败，请重新上传')
		}
	}
	// 获取轮播图
	const returnAllSwiper = async () => {
    const res = await getAllSwiper()
		// console.log(res.data);
		imageSwiperUrl.value = res.data
	}
	returnAllSwiper()

  // -----------------------------------------------------------------------其他管理
	// 部门设置 ，dynamicDepartmentTags是tag的数组，这个数组要传递到数据库
  const dynamicDepartmentTags = ref() 
  const inputDepartmentVisible = ref(false)  // 不可见
  const inputDepartmentValue = ref('') // 获取input的值
	const InputDepartmentRef = ref<InstanceType<typeof ElInput>>()  // 获取input焦点
	// 产品设置
  const dynamicProductTags = ref() 
  const inputProductVisible = ref(false)
  const inputProductValue = ref('')
	const InputProductRef = ref<InstanceType<typeof ElInput>>()

	// 获取部门数据
	const returnDepartment = async() => {
		const res = await getDepartment()  
		dynamicDepartmentTags.value = res.data
	}
	returnDepartment()

  // 点击关闭动态编辑 部门设置 删除
  const handleDepartmentClose = async (tag:string) => {
		// dynamicDepartmentTags.value 数组转换为原始对象(传递到后端必须是原生数据)并将其作为 JSON 字符串传递给 setDepartment 函数
		dynamicDepartmentTags.value.splice(dynamicDepartmentTags.value.indexOf(tag), 1)
		// console.log(toRaw(dynamicDepartmentTags.value)); // (2) ['zl', 'jwj'] 数组
		// console.log(JSON.stringify(toRaw(dynamicDepartmentTags.value))); // ["zl","jwj"] 字符串 
		const res = await setDepartment(JSON.stringify(toRaw(dynamicDepartmentTags.value))) 
		if (res.data.status == 0) {
			ElMessage({
				message: '删除部门成功',
				type: 'success',
			})
		} else {
			ElMessage.error('删除部门失败，请重新输入！')
		}
  }

  // 按下回车键时触发,元素失去焦点时触发
  const handleInputDepartmentConfirm = async () => {
		if (inputDepartmentValue.value) {
			dynamicDepartmentTags.value.push(inputDepartmentValue.value)
			const res = await setDepartment(JSON.stringify(toRaw(dynamicDepartmentTags.value)))
			if (res.data.status == 0) {
				ElMessage({
					message: '添加部门设置成功',
					type: 'success',
				})
			} else {
				ElMessage.error('添加部门失败，请重新输入！')
			}
		}
		inputDepartmentVisible.value = false
		inputDepartmentValue.value = ''
  }

	// 点击部门按钮出现输入框
  const showDepartmentInput = () => {
		inputDepartmentVisible.value = true
		// nextTick 用于在下一次 DOM 更新循环结束之后执行指定的回调函数,输入元素获取焦点
		nextTick(() => {
			InputDepartmentRef.value!.input!.focus()
		})
	}

	// -------------------------------------------------------------
	// 获取产品数据
	const returnProduct = async () => {
		const res = await getProduct()
		dynamicProductTags.value = res.data
	}
	returnProduct()

	// 产品设置，删除
	const handleProductClose =async (tag: string) => {
		dynamicProductTags.value.splice(dynamicProductTags.value.indexOf(tag), 1)
		const res = await setProduct(JSON.stringify(toRaw(dynamicProductTags.value)))
		if (res.data.status == 0) {
			ElMessage({
				message: '删除产品成功',
				type: 'success',
			})
		} else {
			ElMessage.error('删除产品失败，请重新输入！')
		}
	}

	const showProductInput = () => {
		inputProductVisible.value = true
		nextTick(() => {
			InputProductRef.value!.input!.focus()
		})
	}

	const handleInputProductConfirm = async() => {
		if (inputProductValue.value) {
			dynamicProductTags.value.push(inputProductValue.value)
			const res = await setProduct(JSON.stringify(toRaw(dynamicProductTags.value)))
			if (res.data.status == 0) {
				ElMessage({
					message: '添加产品设置成功',
					type: 'success',
				})
			} else {
				ElMessage.error('添加产品失败，请重新输入！')
			}
		}
		inputProductVisible.value = false
		inputProductValue.value = ''
	}
</script>
 
<style lang="scss" scoped>
	// 外壳
	.common-wrapped {
		padding: 0 8px;  // padding: 8px;
		background: #f5f5f5;
		// 计算 减去了头部还有面包屑 + 2X8=16边距
		// height: calc(100vh - 101px);
		height: calc(100vh - 96px);

		// 内容
		.common-content {
			padding: 0 10px;
			height: 100%;
			background: #fff;

			// 账号信息外壳
			.account-info-wrapped {
				display: flex;
				align-items: center;
				padding-left: 50px;
				margin-bottom: 24px;
				font-size: 14px;

				// 账号信息内容
				.account-info-content {
					margin-left: 24px;
					margin-right: 16px;
				}

				// 按钮
				.account-save-button {
					margin-left: 16px;
				}
			}

			// 首页管理外壳
			.home-wrapped {
				padding-left: 50px;
				display: flex;
				flex-direction: column;

				// 提示
				.tips {
					display: flex;
					align-items: center;
					margin-bottom: 8px;

					span {
						font-size: 14px;
						color: silver;
					}
				}

				// 轮播图
				.swiper-wrapped {
					display: flex;
					margin-bottom: 16px;

					// 轮播图名字
					.swiper-name {
						font-size: 14px;
						margin-bottom: 24px;
					}

					.swiper {
						width: 336px;
						height: 88px;  // 图片 96px

					}
				}
			}
		}
	}

	// 其他设置
	.other-set {
		padding-left: 50px;
		font-size: 14px;

		.department-set {
			margin-bottom: 24px;

			span {
				margin-right: 24px;
			}
		}
		
		.product-set {
			
			span {
				margin-right: 24px;
			}
		}
	}

	.el-tag {
    margin: 5px;
	}

	// 标签页
	.demo-tabs>.el-tabs__content {
		padding: 32px;
		color: #6b778c;
		font-size: 32px;
		font-weight: 600;
	}

	// 上传头像
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	// 输入框的长度
	:deep(.el-input) {
		width: 240px;
	}
</style>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>